
#import "RNWXPayModule.h"
#import "WXApi.h"
@implementation RNWXPayModule
{
  RCTPromiseResolveBlock calBackOld;
}
- (instancetype)init
{
  self = [super init];
  if (self) {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hanleWXPay:) name:WXNOT_STAPY object:nil];
  }
  return self;
}
- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
+ (BOOL)requiresMainQueueSetup {
  return YES;
}
-(void)hanleWXPay:(NSNotification *)nsNotification{
    if (calBackOld) {
        if ([@"success" isEqual:nsNotification.object]) {
          calBackOld(@"0");
        }else{
          calBackOld(@"1");
        }
    }
    calBackOld = nil;
}
//#pragma mark-调起微信支付
- (void)WXPayRequest:(NSString *)appId nonceStr:(NSString *)nonceStr package:(NSString *)package partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId timeStamp:(NSString *)timeStamp sign:(NSString *)sign{
  //调起微信支付
  PayReq* wxreq             = [[PayReq alloc] init];
  wxreq.openID              = appId;
  wxreq.partnerId           = partnerId;
  wxreq.prepayId            = prepayId;
  wxreq.nonceStr            = nonceStr;
  wxreq.timeStamp           = [timeStamp intValue];
  wxreq.package             = package;
  wxreq.sign                = sign;
  [WXApi sendReq:wxreq completion:^(BOOL success) {
    
  }];
  
  
}
RCT_EXPORT_MODULE(wxPay)
RCT_REMAP_METHOD(isSupported, // 判断是否支持调用微信SDK
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject){
  
  if (![WXApi isWXAppInstalled]) resolve(@NO);
  else resolve(@YES);
}
RCT_REMAP_METHOD(pay,pay:(NSDictionary *)dic resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject){
  calBackOld = resolve;
  [self WXPayRequest:dic[@"appid"] nonceStr:dic[@"nonce_str"] package:dic[@"package"] partnerId:dic[@"partnerid"] prepayId:dic[@"prepayid"] timeStamp:dic[@"timestamp"] sign:dic[@"sign"]];
  
}
RCT_REMAP_METHOD(goMiniProgram, goMiniProgram:(NSDictionary *)dic resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject){
  __block BOOL isReq = YES;
  
  if ([WXApi isWXAppInstalled]) {
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = [dic objectForKey:@"userName"];  //拉起的小程序的username
    launchMiniProgramReq.path = [dic objectForKey:@"path"];    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
    NSInteger pti = [ [NSString stringWithFormat:@"%@",[dic objectForKey:@"miniProgramType"]] integerValue];
    launchMiniProgramReq.miniProgramType = pti;//拉起小程序的类型
    
    
    
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
      NSLog(@"%d",success);
      if (isReq) {
        isReq = NO;
        resolve( isReq ? @"1" : @"0");
      }
    }];
  }
  
}

@end
  
